/**
 * Module dependencies.
 */

var appPath = global.appPath = __dirname;
var routes = require(appPath + '/routes');
var user = require(appPath + '/routes/user');
var config = require(appPath + '/config.js');
var db = require(appPath + '/lib/db.js');

var path = require('path');
var async = require('async');

var express = require('express');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var compress = require('compression');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var template = require('./lib/template.js');

var app = global.app = express();

// 初始化Redis Session
var store = new RedisStore(config.redis);

// 设置访问端口
app.set('port', config.host.port);

// 设置模板引擎相关
app.use(template(app));

// 开启gzip
app.use(compress());

// 设置静态文件目录(非上传文件)
app.use(express.static(path.join(appPath, 'public'), {
  maxAge: 30 * 24 * 3600 * 1000
}));

app.use(morgan());

// 设置上传文件目录,开启上传文件
app.use(bodyParser({
  keepExtensions: true,
  uploadDir: config.uploadDir
}));

// 表单中间件
app.use(methodOverride());

// cookies分析处理
app.use(cookieParser());

// 开启session
app.use(session({
  secret: config.session_secret,
  key: 'sid',
  store: store
}));

//记录下收到请求的时间
app.use(function (req, res, next) {
  req._getRequestTime = Date.now();
  next();
});

// 为res默认包含site
app.locals.site = config.site;
app.locals.category = {};

// console.log(express.errorHandler().toString());

// development only
if ('development' == app.get('env')) {
  app.use(errorHandler());
  // 暂时禁用默认的,使用自定义的.
  // todo 错误统一处理
  // app.use(function (err, req, res, next) {
  // console.log(err, 'custom');
  // res.send('error');
  // });
}

function redisConnect(done) {
  store.on('disconnect', function () {
    console.log('Redis connect error.');
    process.exit(1);
  });

  store.on('connect', function () {
    console.log('Redis connect success.');
    done(null);
  });
}

function mongodbConnect(done) {
  db.connect(config.db, function (err) {
    if (err) {
      console.error('connect to %s error: ', err.message);
      process.exit(1);
    } else {
      console.log('MongoDB connect success.');
      done(null);
    }
  });
}

// 启动服务
async.parallel([redisConnect, mongodbConnect], function () {
  routes.start(app);
  function callback() {
    console.log('Express server listening on port ' + app.get('port'));
  }

  app.listen(config.host.port, config.host.ip, config.log.file, callback);
});
